<?php
/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：模块公共文件。
 *
 **/


function UpImage($callBack = "image", $width = 100, $height = 100, $image = "")
{

    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
         <input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage($callBack = "image", $width = 100, $height = 100, $image = "")
{
    
    echo '<iframe scrolling="no" frameborder="0" border="0" width=100% onload="this.height=this.contentWindow.document.body.scrollHeight;" src="' . U('Upload/batchpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
		<input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}


/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
*/
function setting($k = 'all')
{
    $cache = S($k);
    //如果缓存不为空直接返回
    if (null != $cache) {
        return $cache;
    }
    $data = '';
    $setting = M('setting');
    //判断是否查询全部设置项
    if ($k == 'all') {
        $setting = $setting->field('k,v')->select();
        foreach ($setting as $v) {
            $config[$v['k']] = $v['v'];
        }
        $data = $config;

    } else {
        $result = $setting->where("k='{$k}'")->find();
        $data = $result['v'];

    }
    //建立缓存
    if ($data) {
        S($k, $data);
    }
    return $data;
}

/**
 * 函数：格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    /*
    *后续整强有力的加密函数
    */
    return md5('Q' . $password . 'W');

}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//获取所有的子级id
function category_get_sons($sid, &$array = array())
{
    //获取当前sid下的所有子栏目的id
    $categorys = M("category")->where("pid = {$sid}")->select();

    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        category_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;

}


/**
 * 获取文章url地址
 * url结构：ttp://wwww.qwadmin.com/分类/子分类/子分类/id.html
 * 使用方法：模板中{:articleUrl(array('aid'=>$val['aid']))}
 *
 *
 * @param $data
 * @return $string
 */
function articleUrl($data)
{
    //如果数组为空直接返回空字符
    if (!$data) {
        return '';
    }
    //如果参数错误直接返回空字符
    if (!isset($data['aid'])) {
        return '';
    }

    $aid = (int)$data['aid'];

    //获取文章信息
    $article = M('article')->where(array('aid' => $aid))->find();
    //获取当前内容所在分类
    $category = M('category')->where(array('id' => $article['sid']))->find();
    //获取当前分类
    $categoryUrl = $category['dir'];
    //遍历获取当前文章所在分类的有上级分类并且组合url
    while ($category['pid'] <> 0) {
        $category = M('category')->where(array('id' => $category['pid']))->find();
        $categoryUrl = $category['dir'] . "/" . $categoryUrl;
        //如果上级分类已经无上级分类则退出
    }

    $categoryUrl = __ROOT__ . "/" . $categoryUrl;
    //组合文章url
    $articleUrl = $categoryUrl . '/' . $aid . ".html";
    return $articleUrl;

}

/**
 * 伪造IP
 * */
function fakeIp(){
	$binfo =array('Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; InfoPath.2; AskTbPTV/5.17.0.25589; Alexa Toolbar)','Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0','Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; Alexa Toolbar)','Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1; SV1)',$_SERVER['HTTP_USER_AGENT']);
	//123.125.68.*
	//125.90.88.*
	
	//定义伪造IP来源段，这里我找的是百度的IP地址
	//复制代码 代码如下:
	$cip = '14.111.58.'.mt_rand(0,254);
	$xip = '125.90.88.'.mt_rand(0,254);
	$header = array(
			'CLIENT-IP:'.$cip,
			'X-FORWARDED-FOR:'.$xip, 
			'Accept: text/html,application/xhtml+xml,application/xml搜索;q=0.9,*/*;q=0.8',
			);
	
	return $header;
}

/**
 * get获取网页内容
 * @header 伪造IP句柄
 * */
function getUrlContent($url,$header,$cookie = null, $is_https = 0){
	$ch = curl_init();
	//$timeout = 5;
	curl_setopt ($ch, CURLOPT_URL, "$url");
	if(!empty($header))
		curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt ($ch, CURLOPT_REFERER, "zsxs.shu22.cn");
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.493.400 QQBrowser/9.0.2524.400");
	curl_setopt ($ch, CURLOPT_ENCODING, "gzip, deflate");	
	//curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	
	if($is_https) {
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	}
	
	if(!empty($cookie))
		curl_setopt($ch,CURLOPT_COOKIE,$cookie);
	$contents = curl_exec($ch);
	curl_close($ch);
	return $contents;
}

/**
 * 保存图片到本地
 * @img_url 网络图片地址
 * */
function getWebImg($img_url = '', $is_https = 0){
	if(empty($img_url))
		return 40003; //图片路径为空
	
	$ch=curl_init();
	$timeout=5;
	curl_setopt($ch,CURLOPT_URL,$img_url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	if($is_https){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	}
	$img=curl_exec($ch);
	curl_close($ch);
	
	//文件目录
	$year = date("Y");
	$month = date("m");
	$day = date("d");
	$save_path_year = "./Public/attached/$year/";
	//如果没有目录创建
	if (!is_dir($save_path_year)) 
		@mkdir($save_path_year);	
	$save_path_month = "./Public/attached/$year/$month/";
	//如果没有目录创建
	if (!is_dir($save_path_month))
		@mkdir($save_path_month);
	$save_path = "./Public/attached/$year/$month/$day/";
	//如果没有目录创建
	if (!is_dir($save_path)) 
		@mkdir($save_path);
	
	//生产文件名
	$file_name = time().rand(0,99999).".jpg";
	$fp2=@fopen($save_path.$file_name,'a');
	fwrite($fp2,$img);
	fclose($fp2);
	unset($img,$img_url);
	
	return array("result"=>1, "save_path"=>substr($save_path, 1, strlen($save_path) - 1), "file_name"=>$file_name);
}

/**
 * 过滤特殊符号
 * */
function specialSignRemove($string){
	$string= trim($string);
	$string= str_replace("、", "", $string);
	$string= str_replace("：", "", $string);
	$string= str_replace("，", "", $string);
	
	return $string;
}

/**
 * 去除字符串的数字
 * */
function digitRemove($string){
	$temp=array('1','2','3','4','5','6','7','8','9','0');
	foreach($temp as $item){
		$string = str_replace($item, "", $string);
	}
	
	return $string;
}

function getWeChatToken($appid = "", $appsecret = "", $token = ""){
	if(!empty($token)) //token没有失效直接获取token
		$access_token= $token;
	elseif(!empty($appid) && !empty($appsecret)){ //token失效了，重新获得token
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
//		echo $url;die;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		$jsoninfo = json_decode($output, true);
		$access_token = $jsoninfo["access_token"];
		
		//setcookie("token",$access_token,time()+7200);
		//S("token",$access_token, array("expire"=>4800));
		//老方法
//		$map["appid"] = $appid;
//		$data["token"] = $access_token;
//		$data["out_time"] = time() + 3600;
//		D("platform")->where($map)->save($data);
		//新方法使用事务和锁表更新
		M()->startTrans(); //开启事务		
		M('platform')->lock(true);
		$map["appid"] = $appid;
		$data["token"] = $access_token;
		$data["out_time"] = time() + 3600;
		$rs = M("platform")->where($map)->save($data);
		if($rs == false)
			M()->rollback();			
		M()->commit();
	}
	else 
		die("bad token set");
	
	return $access_token;
}

/**
 * 微信专用curl
 * @url接口地址
 * @type 1post 默认0get
 * @data post数据包
 * */
function weChatCurl($url, $type=0, $data = array()){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	if($type) {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	$output = curl_exec($ch);
	curl_close($ch);
	$jsoninfo = json_decode($output, true);
	
	return $jsoninfo;
}

/**
 * 置换url
 * */
function urlreplace(){
	$novel_list = D("novel")->where("`from` = '同城群聊'")->select();
	foreach($novel_list as $key=>$item){
		$url = $item["web_from"];
		$url = str_replace("c251", "c28", $url);
		//echo $url."<br>";
		D("novel")->where("id = ".$item["id"])->save(["web_from"=>$url]);
	}
}


/**
  *生成二维码方法
  */

function createQRcode($save_path,$qr_data='PHP QR Code :)',$qr_level='L',$qr_size=4,$save_prefix='qrcode'){
	if(!isset($save_path)) return '';
	//设置生成png图片的路径
	$PNG_TEMP_DIR = & $save_path;
	//导入二维码核心程序
	vendor('PHPQRCODE.phpqrcode');  //注意这里的大小写哦，不然会出现找不到类，PHPQRcode是文件夹名字，class#phpqrcode就代表class.phpqrcode.php文件名
	//检测并创建生成文件夹
	if (!file_exists($PNG_TEMP_DIR)){
		mkdir($PNG_TEMP_DIR);
	}
	$filename = $PNG_TEMP_DIR.'test.png';
	$errorCorrectionLevel = 'L';
	if (isset($qr_level) && in_array($qr_level, array('L','M','Q','H'))){
		$errorCorrectionLevel = & $qr_level;
	}
	$matrixPointSize = 4;
	if (isset($qr_size)){
		$matrixPointSize = & min(max((int)$qr_size, 1), 10);
	}
	if (isset($qr_data)) {
		if (trim($qr_data) == ''){
			die('data cannot be empty!');
		}
		//生成文件名 文件路径+图片名字前缀+md5(名称)+.png
		$filename = $PNG_TEMP_DIR.$save_prefix.md5($qr_data.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
		//开始生成
		QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2,true);
	} else {
		//默认生成
		QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2,true);
	}
	if(file_exists($PNG_TEMP_DIR.basename($filename)))
		return basename($filename);
	else
		return FALSE;
}

/**
  * novel_chapter 中小说章节计算规则
  * 1000以下   12书币
  * 1000-2000  19书币
  * 2000-3000   26书币
  * 3000以上   35书币
  */
 function chapter_money($word_count){
	$money = 14;
	if($word_count == 0)
		$money = 14;
    elseif($word_count < 1000)
		$money = 12;
	elseif($word_count > 1000 && $word_count <= 2000)
		$money = 16;
	elseif($word_count > 2000 && $word_count <= 3000)
		$money = 19;	
	else
		$money = 24;
	
	return $money;
 }



/**
 * 数据库获取session
 */
function getsession(){
    //var_dump(session_id());die;
    $rs = D("session")->field('nickname,img,open_id,sex,domain')->where(["session_id"=>session_id()])->find();

    if(!empty($rs) && $rs["addtime"] > time())
        return ["result"=>1,"data"=>$rs];
    else
        return ["result"=>0];
}







